<template>
  <div class="app-container">
    <t-form
        v-show="showSearch"
        ref="queryRef"
        :model="queryParams"
        class="mb20"
        layout="inline"
    >
      <t-form-item label="活动名称" prop="name">
        <t-input
            v-model="queryParams.name"
            clearable
            placeholder="请输入活动名称"
            style="width: 200px"
            @enter="handleQuery"
        />
      </t-form-item>
      <t-form-item>
        <t-space>
          <t-button theme="primary" @click="handleQuery">
            搜索
            <template #icon>
              <t-icon name="search"/>
            </template>
          </t-button>
          <t-button theme="default" @click="resetQuery">
            重置
            <template #icon>
              <t-icon name="refresh"/>
            </template>
          </t-button>
        </t-space>
      </t-form-item>
    </t-form>

    <t-row :gutter="10" class="mb8">
      <t-col :span="1.5">
        <t-button
            theme="primary"
            @click="handleAdd"
        >新增
          <template #icon>
            <t-icon name="add"/>
          </template>
        </t-button>
      </t-col>
      <right-toolbar
          v-model:showSearch="showSearch"
          @queryTable="getList"
      ></right-toolbar>
    </t-row>

    <t-table
        v-loading="loading"
        :columns="columns"
        :data="list"
        row-key="id"
        stripe
    >
      <template #icon="scope">
        <t-image
            :src="scope.row.icon"
            fit="contain"
            :style="{ width: '120px', height: '120px' }"
        />
      </template>
      <template #action="scope">
        <t-button
            theme="primary"
            variant="text"
            @click="handleUpdate(scope.row)"
        >修改
          <template #icon>
            <t-icon name="edit"/>
          </template>
        </t-button>
        <t-button
            theme="primary"
            variant="text"
            @click="handleDelete(scope.row)"
        >删除
          <template #icon>
            <t-icon name="delete"/>
          </template>
        </t-button>
      </template>
    </t-table>

    <pagination
        v-show="total > 0"
        v-model:limit="queryParams.pageSize"
        v-model:page="queryParams.pageNum"
        :total="total"
        @pagination="getList"
    />

    <t-dialog v-model:visible="open" attach="body" width="780px" :footer="false">
      <template #header>
        <h3 style="margin: auto">{{ title }}</h3>
      </template>
      <t-form ref="levelRef" :data="form" :rules="rules" label-width="140px" @submit="submitForm">
        <t-form-item label="活动名称" name="name" required-mark>
          <t-input
              v-model="form.name"
              placeholder="请输入活动名称"
          />
        </t-form-item>

        <t-form-item label="活动封面" name="image" required-mark>
          <t-upload
              ref="uploadRef"
              action="https://admin.yaojunzhiku.com/prod-api/common/uploadOSS"
              v-model="img"
              sizeLimit="1024KB"
              :max="1"
              theme="image"
              :onSuccess="onSuccess"
              tips="请选择图片文件上传,文件大小不超过1024KB"
              accept="image/*"
          >
          </t-upload>
        </t-form-item>

        <t-form-item label="活动类型" name="typeId" required-mark>
          <t-input
              v-model="form.point"
              placeholder="请输入活动类型"
              type="number"
          />
        </t-form-item>

        <t-form-item label="活动开始时间" name="startAt" required-mark>
          <t-input
              v-model="form.startAt"
              placeholder="请输入活动类型"
              type="number"
          />
        </t-form-item>

        <t-form-item label="活动结束时间" name="endAt" required-mark>
          <t-input
              v-model="form.endAt"
              placeholder="请输入活动类型"
              type="number"
          />
        </t-form-item>

        <t-form-item label="活动总里程" name="distance" required-mark>
          <t-input
              v-model="form.distance"
              placeholder="请输入活动总里程"
              type="number"
          />
        </t-form-item>
        <t-form-item label="活动难度" name="difficulty">
          <t-input
              v-model="form.description"
              placeholder="请输入描述"
          />
        </t-form-item>
        <t-form-item label="活动地址" name="address">
          <t-input
              v-model="form.address"
              placeholder="请输入活动地址"
          />
        </t-form-item>
        <t-form-item label="最大参与人数" name="maxJoin">
          <t-input
              v-model="form.sort"
              placeholder="请输入最大参与人数"
              type="number"
          />
        </t-form-item>
        <t-form-item label="活动详情" name="description">
          <t-input
              v-model="form.description"
              placeholder="请输入最大参与人数"
              type="number"
          />
        </t-form-item>
        <t-form-item style="margin-left: 140px">
          <t-space size="10px">
            <t-button theme="primary" type="submit">提 交</t-button>
            <t-button theme="default" @click="cancel">取 消</t-button>
          </t-space>
        </t-form-item>
      </t-form>
    </t-dialog>
  </div>
</template>
<script setup>

import {getCurrentInstance, reactive, ref, toRefs} from "vue";
import {MessagePlugin} from "tdesign-vue-next";
import {addActivity, getActivity, listActivity, updateActivity} from "@/api/nbot/act";

const {proxy} = getCurrentInstance();


const list = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const total = ref(0);
const title = ref("");
const img = ref([]);

const columns = ref([
  {colKey: "name", title: "活动名称", width: 100, },
  {colKey: "icon", title: "活动封面", width: 100, },
  {colKey: "address", title: "活动地址", width: 100, },
  {colKey: "startAt", title: "活动时间", width: 100, },
  {colKey: "difficulty", title: "活动难度", width: 100, },
  {colKey: "action", title: "操作", width: 100, },
]);

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    name: undefined,
  },
  rules: {
    name: [
      {required: true, message: "活动名称不能为空", trigger: "blur"},
    ],
    image: [
      {required: true, message: "活动封面不能为空", trigger: "blur"},
    ],
  },
});

const {queryParams, form, rules} = toRefs(data);


const onSuccess = ({response}) => {
  form.value.icon = response.url;
}

/** 查询列表 */
function getList() {
  loading.value = true;
  listActivity(queryParams.value).then((response) => {
    list.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

/** 取消按钮 */
function cancel() {
  open.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = {
    name: undefined,
    image: undefined,
    typeId: undefined,
    startAt: undefined,
    endAt: undefined,
    distance: undefined,
    difficulty: undefined,
    address: undefined,
    maxJoin: 50,
    description: undefined,
    fee: undefined,
  };
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加活动";
}

/**修改按钮操作 */
function handleUpdate(row) {
  reset();
  const id = row.id || ids.value;
  getActivity(id).then((response) => {
    form.value = response.data;
    img.value = [{
      url: response.data.icon,
    }];
    open.value = true;
    title.value = "修改添加活动";
  });
}

/** 提交按钮 */
const submitForm = ({ validateResult, firstError }) => {
  // 检查表单验证结果
  if (validateResult === true) {
    const submitData = {
      ...form.value,
    };

    if (form.value.id !== undefined) {
      updateActivity(submitData).then((response) => {
        MessagePlugin.success("修改成功");
        open.value = false;
        getList();
      }).catch((error) => {
        MessagePlugin.error("修改失败");
      });
    } else {
      addActivity(submitData).then((response) => {
        MessagePlugin.success("新增成功");
        open.value = false;
        getList();
      }).catch((error) => {
        MessagePlugin.error("新增失败");
      });
    }
  } else {
    // 验证失败，显示错误信息
    console.log('Validation errors:', validateResult);
    if (firstError) {
      MessagePlugin.warning(firstError);
    } else {
      MessagePlugin.warning("请检查表单输入");
    }
  }
}

/** 删除按钮操作 */
function handleDelete(row) {
  const id = row.id || ids.value;
  proxy.$modal
      .confirm('是否确认删除编号为"' + id + '"的数据项？')
      .then(function () {
        return delLevel(id);
      })
      .then(() => {
        getList();
        proxy.$modal.msgSuccess("删除成功");
      })
      .catch(() => {
      });
}

getList();
</script>
